var path = require("path");
const moment = require('moment')
var articleDAO = require(path.join(process.cwd(), "dao/ArticleDAO"));

/**
 * 获取所有文章
 * @param  {[type]}   conditions 查询条件
 * 查询条件统一规范
 * conditions
	{
		"query" : 关键词查询,
		"pagenum" : 页数,
		"pagesize" : 每页长度
	}
 * @param  {Function} cb         回调函数
 */
module.exports.getAllArticles = function (conditions, cb) {
	if (!conditions) return err

	// 通过关键词获取文章数量
	articleDAO.countByKey(conditions["query"], function (err, count) {
		key = conditions["query"];

		articleDAO.findByKey(key, function (err, articles) {
			var retArticles = [];
			for (idx in articles) {
				var article = articles[idx];
				retArticles.push({
					"id": article.art_id,
					"title": article.title,
					"summary": article.summary,
					"content": article.content,
					"classifica": article.classifica,
					"tag": article.tag,
					"created_time": moment(article.created_time).format("YYYY-MM-DD"),
					"at_state": 1
				});
			}
			var resultDta = {};
			resultDta["total"] = count;
			resultDta["articles"] = retArticles;
			cb(err, resultDta);
		});
	});
}

/**
 * 通过文章 ID 获取文章信息
 * 
 * @param  {[type]}   id 文章 ID
 * @param  {Function} cb 回调函数
 */
module.exports.getArticle = function (id, cb) {
	articleDAO.show(id, function (err, article) {
		if (err) return cb(err);
		if (!article) return cb("该博客不存在");
		cb(
			null,
			{
				"id": article.art_id,
				"title": article.title,
				"summary": article.summary,
				"content": article.content,
				"classifica": article.classifica,
				"tag": article.tag,
				"created_time": moment(article.created_time).format("YYYY-MM-DD"),
			}
		);
	});
}

module.exports.createdArticle = function (params, cb) {
	articleDAO.exists(params.title, function (err, isExists) {
		if (err) return err
		if (isExists) cb('此标题博客已存在')
		console.log('params.tag' + params.tag);

		articleDAO.create({
			"title": params.title,
			"summary": params.summary,
			"content": params.content,
			"classifica": params.classifica,
			"tag": params.tag.join('，'),
			"created_time": new Date(),
		},
			function (err, article) {
				console.log(err);
				if (err) return cb("发布失败"+err);
				result = {
					"title": article.title,
					"summary": article.summary,
					"content": article.content,
					"classifica": article.classifica,
					"tag": article.tag,
					"created_time": article.created_time,
				};
				cb(null, result);
			})
	})
}